package com.stox.client.ui.javafx.widget.dynamic.column.barValue;

import java.util.List;

import javafx.beans.property.ObjectProperty;
import javafx.scene.control.TableColumn.CellDataFeatures;

import com.stox.client.api.data.provider.BarClient;
import com.stox.client.ui.javafx.widget.dynamic.column.AbstractCellValueFactory;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.enumeration.BarSpan;
import com.stox.shared.core.model.filter.BarCriteria;
import com.stox.shared.core.model.intf.HasScrip;

public class BarValueCellValueFactory<S extends HasScrip> extends AbstractCellValueFactory<S, Double> {

	private final BarClient barClient;
	
	public BarValueCellValueFactory(BarClient barClient) {
		this.barClient = barClient;
	}
	
	@Override
	public void fetchValue(final CellDataFeatures<S, Double> cellDataFeatures, final ObjectProperty<Double> valueProperty) {
		new Thread(){
			public void run() {
					S hasScrip = cellDataFeatures.getValue();
					if(null != hasScrip && null != hasScrip.getScrip() && null != hasScrip.getScrip().getId()){
						BarValueColumn<S> column = (BarValueColumn<S>)cellDataFeatures.getTableColumn();
						BarSpan barSpan = column.getBarSpan();
						List<Bar> bars =barClient.find(new BarCriteria(hasScrip.getScrip().getId(), barSpan.previous(), barSpan.next(), barSpan));
						if(null != bars && !bars.isEmpty()){
							valueProperty.set(column.getBarValue().get(bars.get(0)));
						}
					}
			};
		}.start();
	}
}